package com.action.admin.image;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;

import com.action.BaseAction;
import com.conf.CommonConfig;
import com.dao.ImageDao;
import com.entity.Employee;
import com.entity.ImageInfo;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.util.AppUtil;
import com.util.ImageUtil;


import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;

/**
 * 
 * @author Administrator
 * 
 */
// @ParentPackage("json-default")
@ParentPackage("extendsjson-default")
@Namespace("/image")
@ResultPath("/WEB-INF/pages")
public class ImageAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(ImageAction.class);

	/**
	 * 到上传图片页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "uploadimage", results = { @Result(name = "success", location = "image_upload.jsp") })
	public String uploadimage() throws Exception {
		return SUCCESS;
	}

	/**
	 * 图片上传，成功后返回图片名
	 * 
	 * @return
	 */
	@Action(value = "addImg2", results = { @Result(name = "success", type = "json") })
	public String addImg2() {
		Employee emp = (Employee) session("userinfo");
		if(emp == null)
			emp = new Employee();
		emp.setClientid(700040278);
		emp.setCityid(10);
		ImageInfo imgInfo = null;
		long imageid = 0;
		long id = System.currentTimeMillis();
		String img_type = "jpg";

		// 文件名称
		String small_name = String.valueOf(id) + "_1." + img_type;
		String midd_name = String.valueOf(id) + "_2." + img_type;
		String big_name = String.valueOf(id) + "_3." + img_type;
		String source = id + "_0." + img_type;
		try {
			if (emp != null) {
				int clientid = emp.getClientid();
				int cityid = emp.getCityid();
				String path = ImageUtil.getPathById(CommonConfig.getParamete("IMAGE_PATH"), clientid, "images");

				File old_file = new File(path + big_name);
				try {
					FileUtils.copyFile(fileInput, old_file);
					//ImageUtil.cutImg(old_file.getAbsolutePath(), path + source, w, h, x, y);
					ImageUtil.CutPic(clientid, old_file, path + small_name, path + midd_name, path + big_name, path);

					imgInfo = new ImageInfo();
					imgInfo.setClientid(clientid);
					imgInfo.setCityid(cityid);
					imgInfo.setPicname("" + id);
					imgInfo.setStatus(Short.valueOf("0"));
					imgInfo.setUploadtime(new Date());
					imgInfo.setTitle(picName);
					imageDao.save(imgInfo);
					// 获取图像编号
					imageid = imgInfo.getImageid();
				} catch (Exception e) {
					LOG.error(e.getMessage(), e);
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", imageid);
				map.put("name", "" + id);
				map.put("url", path);
				map.put("picName", picName);
				map.put("flag", flag);
				System.out.println("map== " + AppUtil.gson().toJson(map));
				// this.Object2Json(map);
				this.outString(AppUtil.gson().toJson(map));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 图片上传，成功后返回图片名
	 * 
	 * @return
	 */
	@Action(value = "addImg", results = { @Result(name = "success", type = "json") })
	public String addImg() {
		Employee emp = (Employee) session("userinfo");
		ImageInfo imgInfo = null;
		long imageid = 0;
		long id = System.currentTimeMillis();
		String img_type = "jpg";

		// 文件名称
		String small_name = String.valueOf(id) + "_1." + img_type;
		String midd_name = String.valueOf(id) + "_2." + img_type;
		String big_name = String.valueOf(id) + "_3." + img_type;
		String source = id + "_0." + img_type;
		try {
			if (emp != null) {
				int clientid = emp.getClientid();
				int cityid = emp.getCityid();
				String path = ImageUtil.getPathById(CommonConfig.getParamete("IMAGE_PATH"), clientid, "images");

				File old_file = new File(path + big_name);
				try {
					FileUtils.copyFile(fileInput, old_file);
					ImageUtil.cutImg(old_file.getAbsolutePath(), path + source, w, h, x, y);
					ImageUtil.CutPic(clientid, new File(path + source), path + small_name, path + midd_name, path + big_name, path);

					imgInfo = new ImageInfo();
					imgInfo.setClientid(clientid);
					imgInfo.setCityid(cityid);
					imgInfo.setPicname("" + id);
					imgInfo.setStatus(Short.valueOf("0"));
					imgInfo.setUploadtime(new Date());
					imgInfo.setTitle(picName);
					imageDao.save(imgInfo);
					// 获取图像编号
					imageid = imgInfo.getImageid();
				} catch (Exception e) {
					LOG.error(e.getMessage(), e);
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", imageid);
				map.put("name", "" + id);
				map.put("url", path);
				map.put("picName", picName);
				map.put("flag", flag);
				System.out.println("map== " + AppUtil.gson().toJson(map));
				// this.Object2Json(map);
				this.outString(AppUtil.gson().toJson(map));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	/**
	 * kindeditor图片上传，成功后返回图片名
	 * 
	 * @return
	 */
	@Action(value = "addImg3", results = { @Result(name = "success", type = "json") })
	public String kindEditorUploadImg() {
		Employee emp = (Employee) session("userinfo");
		ImageInfo imgInfo = null;
		long imageid = 0;
		long id = System.currentTimeMillis();
		String img_type = "jpg";
		if(emp == null)emp = new Employee();
		emp.setCityid(10);
		emp.setClientid(700040278);
		w = this.getIntValue("imgWidth", 0, 0);
		h = this.getIntValue("imgWidth",0, 0);
		// 文件名称
		String small_name = String.valueOf(id) + "_1." + img_type;
		String midd_name = String.valueOf(id) + "_2." + img_type;
		String big_name = String.valueOf(id) + "_3." + img_type;
		String source = id + "_0." + img_type;
		try {
			if (emp != null) {
				int clientid = emp.getClientid();
				int cityid = emp.getCityid();
				String path = ImageUtil.getPathById(CommonConfig.getParamete("IMAGE_PATH"), clientid, "images");

				File old_file = new File(path + big_name);
				try {
					FileUtils.copyFile(imgFile, old_file);
					//ImageUtil.cutOnePic(file, no1_path, width_1, height_1)
					//ImageUtil.cutImg(old_file.getAbsolutePath(), path + source, w, h, x, y);
					ImageUtil.CutPic(clientid, old_file, path + small_name, path + midd_name, path + big_name, path);

					imgInfo = new ImageInfo();
					imgInfo.setClientid(clientid);
					imgInfo.setCityid(cityid);
					imgInfo.setPicname("" + id);
					imgInfo.setStatus(Short.valueOf("0"));
					imgInfo.setUploadtime(new Date());
					imgInfo.setTitle(picName);
					imageDao.save(imgInfo);
					// 获取图像编号
					imageid = imgInfo.getImageid();
				} catch (Exception e) {
					LOG.error(e.getMessage(), e);
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("error", 0);
				map.put("url", "/testimg/700/040/278/images/"+midd_name);
				map.put("id", imageid);
				map.put("name", "" + id);
				map.put("picName", picName);
				map.put("flag", flag);
				System.out.println("map== " + AppUtil.gson().toJson(map));
				// this.Object2Json(map);
				this.Object2Json(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * kindeditor图片上传，成功后返回图片名
	 * 
	 * @return
	 */
	@Action(value = "findImage", results = { @Result(name = "success", type = "json") })
	public String findImage() {
		Employee emp = (Employee) session("userinfo");
		if (emp == null)
			emp = new Employee();
		emp.setCityid(10);
		emp.setClientid(700040278);
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		Map result = new HashMap();
		try {
			list = imageDao.findImageListByClientId(700040278);
			// 遍历目录取的文件信息
			for (ImageInfo info : list) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				hash.put("is_dir", false);
				hash.put("has_file", false);
				hash.put("filesize", 1L);
				hash.put("is_photo", true);
				hash.put("filetype", ".jpg");
				hash.put("filename", info.getPicname()+"_2.jpg");
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(info.getUploadtime()));
				fileList.add(hash);
			}
			
			result.put("moveup_dir_path", "/testimg/700/040/278/images/");
			result.put("current_dir_path","/testimg/700/040/278/images/");
			result.put("current_url", "/testimg/700/040/278/images/");
			result.put("total_count", fileList.size());
			result.put("file_list", fileList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.Object2Json(result);
		return SUCCESS;
	}
	
	
	
	public String uploadPic(){
		
		return null;
	}
//	/**
//	 * 对每个上传的文件进行处理
//	 * 
//	 * @param file
//	 *            上传的文件
//	 * @param restaurantid
//	 *            餐厅ID
//	 * @param path
//	 *            路径
//	 * @param altText
//	 *            图片名称
//	 * @param clientempid
//	 *            用户ID
//	 * @param flag
//	 *            图片类型状态0：普通图片 1：头图，2：logo 4:banner图
//	 * 
//	 */
//	private void uploadFile(File file, int restaurantid, String path, String altText, int clientempid, int flag) {
//		long id = System.currentTimeMillis();
//		String img_type = "jpg";
//
//		// 文件名称
//		String small_name = String.valueOf(id) + "_1." + img_type;
//		String midd_name = String.valueOf(id) + "_2." + img_type;
//		String big_name = String.valueOf(id) + "_3." + img_type;
//		String source = id + "_0." + img_type;
//
//		// 头图
//		if (flag == 1) {
//			small_name = "default." + img_type;
//			midd_name = "default_1." + img_type;
//		}
//
//		// logo 图
//		if ((altText != null && altText.equals("LOGO")) || flag == 2) {
//			small_name = "logo_1." + img_type;
//			midd_name = "logo_2." + img_type;
//			big_name = "logo_3." + img_type;
//		}
//		// banner图
//		if (flag == 4) {
//			small_name = "banner_1." + img_type;
//			midd_name = "banner_2." + img_type;
//			big_name = "banner_3." + img_type;
//		}
//
//		File old_file = new File(path + big_name);
//		try {
//			FileUtils.copyFile(file, old_file);
//			ImageUtil.cutImg(old_file.getAbsolutePath(), path + source, w, h, x, y);
//			ImageUtil.CutPic(restaurantid, new File(path + source), path + small_name, path + midd_name, path + big_name, path);
//
//			// 服务器加水印
//			this.pressImage("/data/images/b.gif", path + big_name);
//			this.pressImage("/data/images/s.gif", path + midd_name);
//		} catch (IOException e) {
//			LOG.error("上传图片失败", e);
//		} catch (Exception e) {
//			LOG.error("图片压缩失败", e);
//		}
//	}

	/**
	 * 添加水印
	 * 
	 * @param Imagename_biao
	 * @param ImgName
	 */
	public boolean pressImage(String pressImg, String targetImg) {
		FileOutputStream out = null;
		boolean flag = false;
		try {
			// File _file = new File(targetImg);
			// Image src = ImageIO.read(_file);
			ImageIcon imgIcon = new ImageIcon(targetImg);
			Image src = imgIcon.getImage();
			int wideth = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
			// Graphics g = image.createGraphics();
			Graphics2D g = image.createGraphics();
			g.drawImage(src, 0, 0, wideth, height, null);

			// 水印文件
			// File _filebiao = new File(pressImg);
			// Image src_biao = ImageIO.read(_filebiao);
			ImageIcon _filebiao = new ImageIcon(pressImg);
			Image src_biao = _filebiao.getImage();
			int wideth_biao = src_biao.getWidth(null);
			int height_biao = src_biao.getHeight(null);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, (float) 0.5));
			g.drawImage(src_biao, wideth - wideth_biao, height - height_biao, wideth_biao, height_biao, null);

			g.dispose();
			out = new FileOutputStream(targetImg);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
			param.setQuality(100f, true);
			encoder.encode(image, param);
			// encoder.encode(image);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return flag;
	}

	/**
	 * 删除图片
	 * 
	 * @return
	 */
	@Action(value = "delimage", results = { @Result(name = "success", type = "json") })
	public String delimage() {
		try {
			ImageInfo info = imageDao.findImageInfoById(imageId+"");
			imageDao.deleteObject(info);
		} catch (Exception e) {
			e.printStackTrace();
			this.outString("1");
		}
		this.outString("0");
		return SUCCESS;
	}

	/**
	 * 修改图片名称
	 * 
	 * @return
	 */
	@Action(value = "updatePicname", results = { @Result(name = "success", type = "json") })
	public String updatePicName() {
		try {
			ImageInfo info = imageDao.findImageInfoById(imageId+"");
			info.setTitle(picName);
			imageDao.save(info);
		} catch (Exception e) {
			e.printStackTrace();
			this.outString("1");
		}
		this.outString("0");
		return SUCCESS;
	}

	private ImageDao imageDao = (ImageDao) ioc.newInstance(ImageDao.class);

	private File fileInput,filedata,imgFile;
	private int x, y, w, h, flag;
	private List<File> upload = null;
	private List<String> title = null;
	private Long imageId = null;
	private String picName;
	private List<ImageInfo> list;

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public File getFiledata() {
		return filedata;
	}

	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	public String getPicName() {
		return picName;
	}

	public void setPicName(String picName) {
		this.picName = picName;
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public List<File> getUpload() {
		return upload;
	}

	public void setUpload(List<File> upload) {
		this.upload = upload;
	}

	public List<String> getTitle() {
		return title;
	}

	public void setTitle(List<String> title) {
		this.title = title;
	}

	public Long getImageId() {
		return imageId;
	}

	public void setImageId(Long imageId) {
		this.imageId = imageId;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getW() {
		return w;
	}

	public void setW(int w) {
		this.w = w;
	}

	public int getH() {
		return h;
	}

	public void setH(int h) {
		this.h = h;
	}

	public File getFileInput() {
		return fileInput;
	}

	public void setFileInput(File fileInput) {
		this.fileInput = fileInput;
	}
}
